import { styled } from '@umijs/max'
import { Button, Col, Divider, Form, Input, Modal, Row, Select, Space, Table } from 'antd'
import { useEffect, useState } from 'react'
import { useRequest } from 'ahooks'
import { PAGINATION_CONFIG } from '@/constants'
import type { ColumnsType } from 'antd/es/table'
import { Access } from '@umijs/max'
import { CloseCircleFilled } from '@ant-design/icons'
import { queryGoodsList, queyGoodsDetail } from '@/services/goods'
import { GoodsState, GoodsType } from '@/constants/enums/goods'

const ModalContent = styled.div`
  display: flex;
  flex-direction: column;
  gap: 20px;

  .ant-form-item {
    margin: 0;
  }
`

export const SelectModal: React.FC<GoodsSelector.ModalProps> = props => {
  const [searchForm] = Form.useForm()
  const [searchParams, setSearchParams] = useState<Goods.QueryListParams>({
    pageNum: 1, pageSize: 10, goodsType: GoodsType.基础商城, state: GoodsState.上架
  });
  const list = useRequest(() => queryGoodsList(searchParams), {
    ready: !!props.open,
    refreshDeps: [searchParams],
  })
  const stocks = useRequest(queyGoodsDetail, {manual: true})
  const [selected, setSelected] = useState<GoodsSelector.Selected>({});

  const columns: ColumnsType<Goods.Entity> = [
    {
      title: '商品名称',
      dataIndex: 'goodsName',
      width: 100,
    },
    {
      title: '价格(元)',
      dataIndex: 'goodsPrice',
      width: 100,
      render: val => val || 0,
    },
    {
      title: '库存',
      dataIndex: 'goodsNum',
      width: 100,
      render: val => val || 0,
    },
    {
      title: '销量',
      dataIndex: 'sale',
      width: 100,
      render: val => val || 0,
    },
    {
      title: '状态',
      dataIndex: 'goodsState',
      width: 100,
      render: goodsState => goodsState === GoodsState.上架 ? '上架中' : '待上架',
    },
  ]

  const onFinish = (formValues: Goods.QueryListParams) => {
    setSearchParams({
      ...searchParams,
      ...formValues,
      pageNum: 1,
    })
  }
  const onReset = () => {
    searchForm.resetFields()
  }
  const onCancel = () => {
    props.onClose?.()
  }
  const onOk = () => {
    let result: GoodsSelector.Value[] = []
    Object.values(selected).forEach((val: GoodsSelector.Value[]) => result = result.concat(val))
    props.onSelect?.(result)
    onCancel()
  }
  const onExpand = (expand: boolean, record: Goods.Entity) => {
    if (expand) {
      stocks.runAsync({id: record.goodsId}).then(res => {
        record.goodsStocks = res.data.goodsStocks
      })
    }
  }

  useEffect(() => {
    if (props.open && props.initValue) {
      setSelected({1: props.initValue.map(item => ({...item, id: parseInt(item.id)}))})
    } else {
      setSelected({})
    }
  }, [props.open]);

  return (
    <Modal
      open={props.open}
      width={800}
      title='选择商品'
      onOk={onOk}
      onCancel={onCancel}
      destroyOnClose
    >
      <ModalContent>
        <Form form={searchForm} onFinish={onFinish} onReset={onReset} initialValues={{state: GoodsState.上架}}>
          <Row gutter={[20, 20]}>
            <Col span={6}>
              <Form.Item label='商品名称' name='goodsName'>
                <Input placeholder='请输入' />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label='商品状态' name='state'>
                <Select placeholder='请选择' options={[
                  {label: '上架中', value: GoodsState.上架},
                  {label: '待上架', value: GoodsState.下架},
                ]} allowClear />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Space>
                <Button type='primary' htmlType='submit' loading={list.loading}>筛选</Button>
                <Button onClick={onReset}>重置</Button>
              </Space>
            </Col>
          </Row>
        </Form>
        <Table<Goods.Entity>
          rowKey='goodsId'
          loading={list.loading || stocks.loading}
          dataSource={list.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: list.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
          rowSelection={props.target === 'goods' ? {
            type: props.type,
            selectedRowKeys: selected[searchParams.pageNum]?.map(it => it.id),
            onChange: (_, rows) => {
              setSelected({1: rows.map(it => ({id: it.goodsId, name: it.goodsName, inventory: it.goodsNum || 0, price: it.goodsPrice}))})
            }
          } : undefined}
          expandable={props.target === 'stock' ? {
            rowExpandable: () => true,
            onExpand: onExpand,
            expandedRowRender: (record) => {
              return <Table<Goods.GoodsStock>
                rowKey='stockId'
                size='small'
                dataSource={record.goodsStocks}
                columns={[
                  {
                    title: '商品名称',
                    dataIndex: 'stockName',
                    width: 100,
                  },
                  {
                    title: '价格(元)',
                    dataIndex: 'stockPrice',
                    width: 100,
                    render: val => val || 0,
                  },
                  {
                    title: '可用库存',
                    key: 'inventory',
                    width: 100,
                    render: (_, record) => {
                      return record.stockNum || 0
                    },
                  },
                ]}
                scroll={{y: 700, x: 'max-content'}}
                pagination={false}
                rowSelection={{
                  type: props.type,
                  selectedRowKeys: selected[searchParams.pageNum]?.map(it => it.id),
                  onChange: (_, rows) => {
                    setSelected({1: rows.map(it => ({
                      id: it.stockId, 
                      goodsId: it.goodsId,
                      name: `${record.goodsName} ${it.stockName}`, 
                      price: it.stockPrice || 0,
                      inventory: it.stockNum || 0
                    }))})
                  }
                }}
              />
            }
          } : undefined}
        />
      </ModalContent>
    </Modal>
  )
}

const GoodsSelect: React.FC<GoodsSelector.Props> = props => {
  const [open, setOpen] = useState(false)

  const close = () => {
    setOpen(false)
  }

  const allowClear = () => {
    props.onChange?.(undefined)
  }
  
  return <div>
    <Access accessible={props.type === 'checkbox'}>
      <a onClick={() => setOpen(true)}>选择商品</a>
    </Access>
    <Access accessible={props.type === 'radio'}>
      <div style={{display: 'flex', gap: 8, alignItems: 'center'}}>
        <Access accessible={!!props.button}>
          <Access accessible={!!props.value}>
            <Input style={props.style} value={props.value?.[0]?.name} readOnly disabled={props.disabled} />
            <Space size={0} 
              style={{flexShrink: 0}}
              split={<Divider type='vertical' style={{borderColor: 'var(--ant-color-primary)'}} />}
            >
              <a onClick={() => setOpen(true)}>修改</a>
              <a onClick={allowClear}>清除</a>
            </Space>
          </Access>
        </Access> 
        <Access accessible={!props.button}>
          <Input
            placeholder='请选择'
            value={props.value?.[0]?.name}
            disabled={props.disabled}
            readOnly
            variant={props.variant}
            style={props.style}
            addonAfter={props.disabled ? '选择' : <a onClick={() => setOpen(true)}>选择</a>}
            suffix={!!props.allowClear && !!props.inline && !!props.value?.length ? <CloseCircleFilled onClick={allowClear} style={{color: '#ccc'}} /> : undefined}
          />
          <Access accessible={!!props.allowClear && !props.inline}>
            <a onClick={allowClear}>清除</a>
          </Access>
        </Access>
      </div>
    </Access>
    <SelectModal
      open={open}
      onClose={close}
      initValue={props.value}
      onSelect={props.onChange}
      type={props.type || 'radio'}
      target={props.target}
    />
  </div>
}

export default GoodsSelect
